jQuery(function($) {
	
	$.fn.dataTable.Buttons.defaults.dom.container.className = 'dt-buttons btn-overlap btn-group btn-overlap';

	//table checkboxes
	$('th input[type=checkbox], td input[type=checkbox]').prop('checked', false);

	$(document).on('click', '#dynamic-table .dropdown-toggle', function(e) {
		e.stopImmediatePropagation();
		e.stopPropagation();
		e.preventDefault();
	});
	
	//And for the first simple table, which doesn't have TableTools or dataTables
	//select/deselect all rows according to table header checkbox
	var active_class = 'active';
	$('#simple-table > thead > tr > th input[type=checkbox]').eq(0).on('click', function(){
		var th_checked = this.checked;//checkbox inside "TH" table header
		
		$(this).closest('table').find('tbody > tr').each(function(){
			var row = this;
			if(th_checked) $(row).addClass(active_class).find('input[type=checkbox]').eq(0).prop('checked', true);
			else $(row).removeClass(active_class).find('input[type=checkbox]').eq(0).prop('checked', false);
		});
	});
	
	//select/deselect a row when the checkbox is checked/unchecked
	$('#simple-table').on('click', 'td input[type=checkbox]' , function(){
		var $row = $(this).closest('tr');
		if($row.is('.detail-row ')) 
			return;
		if(this.checked) $row.addClass(active_class);
		else $row.removeClass(active_class);
	});
	
	/***************/
	$('.show-details-btn').on('click', function(e) {
		e.preventDefault();
		$(this).closest('tr').next().toggleClass('open');
		$(this).find(ace.vars['.icon']).toggleClass('fa-angle-double-down').toggleClass('fa-angle-double-up');
	});
	/***************/
	
	/**
	//add horizontal scrollbars to a simple table
	$('#simple-table').css({'width':'2000px', 'max-width': 'none'}).wrap('<div style="width: 1000px;" />').parent().ace_scroll(
	  {
		horizontal: true,
		styleClass: 'scroll-top scroll-dark scroll-visible',//show the scrollbars on top(default is bottom)
		size: 2000,
		mouseWheelLock: true
	  }
	).css('padding-top', '12px');
	*/
})

/**
 * 打开添加用户的窗口
 * @returns
 */
$('#add-user-btn').on('click', function(){
	$('#userModelLabel').html('添加用户');
	$('#form-id').val('');
	$('#form-username').val('');
	$('#form-password').val('');
	$('#form-nickname').val('');
	$('#form-age').val('');
	$("input[type=radio][name=sex][value='0']").prop("checked", "checked");
	$("input[type=radio][name=sex][value='1']").prop("checked", "");
	$('#form-phone').val('');
	$('#form-email').val('');
	//$('#form-faceImage-div').addClass('hidden');
	$('#form-address').val('');
	$("input[type=radio][name=status][value='0']").prop("checked", "checked");
	$("input[type=radio][name=status][value='1']").prop("checked", "");
	$("input[type=radio][name=status][value='2']").prop("checked", "");
	showRoleList();
	$('#userModel').modal('show');
});

/**
 * 动态显示所有的角色列表
 * @returns
 */
function showRoleList(){
	$.ajax({
		url: '/admin/sys/role/ajaxRolesList',
		data:{"available": true},
		method: 'post',
		dataType: 'json',
		async: false,
		success:function(obj){
			if(obj.status == 200 && obj.data.length > 0){
				for(var i = 0; i < obj.data.length; i++){
					$('#user-role').append('<label><input name="role" type="checkbox" class="ace" value="' + obj.data[i].id + '"/><span class="lbl"> ' + obj.data[i].name + '</span></label>');
				}
			}
		},
		error:function(obj){
			gritterError("您无权操作此项");
		}
	});
}

/**
 * 查询用户拥有的角色信息
 * @param userId
 * @returns
 */
function showRoleListById(userId){
	var userRoleIds = [];
	$.ajax({
		url: '/admin/sys/role/ajaxRolesList',
		data: {"userId": userId, "available": true},
		method: 'post',
		dataType: 'json',
		async: false,
		success:function(obj){
			if(obj.status == 200 && obj.data.length > 0){
				for(var i = 0; i < obj.data.length; i++){
					userRoleIds.push(obj.data[i].id);
				}
			}
		},
		error:function(obj){
			gritterError("您无权操作此项");
		}
	});
	return userRoleIds;
}

/**
 * 关闭表单modal的时候清空角色信息
 * @returns
 */
$('#userModel').on('hide.bs.modal', function () {
	$("#user-role").html('');
})

/**
 * 打开修改用户信息弹窗
 * @param obj
 * @returns
 */
function updateUser(obj){
	$.ajax({
		url: '/admin/sys/user/ajaxUserInfo',
		data: {"userId": obj.id.replace('update-','').replace('-update','')},
		dataType: 'json',
		async: false,
		success:function(obj){
			if(obj.status == 200){
				$('#userModelLabel').html('修改用户');
				$('#form-id').val(obj.data.id);
				$('#form-username').val(obj.data.username);
				$('#form-password').val(obj.data.password);
				$('#form-nickname').val(obj.data.nickname);
				$('#form-age').val(obj.data.age);
				if(obj.data.sex == '0'){
					$("input[type=radio][name=sex][value='0']").prop("checked", "checked");
					$("input[type=radio][name=sex][value='1']").prop("checked", "");
				}else if(obj.data.sex == '1'){
					$("input[type=radio][name=sex][value='1']").prop("checked", "checked");
					$("input[type=radio][name=sex][value='0']").prop("checked", "");
				}
				$('#form-phone').val(obj.data.phone);
				$('#form-email').val(obj.data.email);
				//$('#form-faceImage-div').removeClass('hidden');
				$('#form-address').val(obj.data.address);
				if(obj.data.status == '0'){
					$("input[type=radio][name=status][value='0']").prop("checked", "checked");
					$("input[type=radio][name=status][value='1']").prop("checked", "");
					$("input[type=radio][name=status][value='2']").prop("checked", "");
				}else if(obj.data.status == '1'){
					$("input[type=radio][name=status][value='0']").prop("checked", "");
					$("input[type=radio][name=status][value='1']").prop("checked", "checked");
					$("input[type=radio][name=status][value='2']").prop("checked", "");
				}else if(obj.data.status == '2'){
					$("input[type=radio][name=status][value='0']").prop("checked", "");
					$("input[type=radio][name=status][value='1']").prop("checked", "");
					$("input[type=radio][name=status][value='2']").prop("checked", "checked");
				}
				showRoleList();
				var userRoleIds = showRoleListById(obj.data.id);
				for(var i = 0; i < userRoleIds.length; i++){//将用户拥有的角色信息默认选中
					$("input[type=checkbox][name=role][value='"+userRoleIds[i]+"']").attr("checked", "true");
				}
				$('#userModel').modal('show');//显示修改的modal窗口
			}else{
				gritterError(obj.msg);
			}
		},
		error:function(obj){
			gritterError("您无权操作此项");
		}
	});
}

/**
 * 表单提交用户信息
 * @returns
 */
$('#submit-user-info').on('click',function(){
	var type = $('#userModelLabel').html();
	var url = '';
	if(type == '添加用户'){
		url = '/admin/sys/user/save';
	}else if(type == '修改用户') {
		url = '/admin/sys/user/update';
	}
	$.ajax({
		url: url,
		data: $('#user-info-form').serialize(),
		method: 'post',
		dataType: 'json',
		async: false,
		success:function(obj){
			if(obj.status == 200){
				gritterSuccess(obj.data);
				window.location.reload();
			}else {
				gritterError(obj.msg);
			}
		},
		error:function(obj){
			gritterError("您无权操作此项");
		}
	});
});

/**
 * 删除用户
 * @param obj
 * @returns
 */
function delUser(obj){
	$( "#dialog-confirm" ).removeClass('hide').dialog({
		resizable: false,
		width: '320',
		modal: true,
		title: "系统提示",
		title_html: true,
		buttons: [
			{
				html: "<i class='ace-icon fa fa-trash-o bigger-110'></i>删除",
				"class" : "btn btn-danger btn-minier",
				click: function() {
					var id = obj.id.replace('del-','').replace('-del','');
					$.ajax({
						url: '/admin/sys/user/delete',
						data: {"id":id},
						dataType: 'json',
						async: false,
						success:function(obj){
							if(obj.status == 200){
								gritterSuccess(obj.data);
								//$('#userModel').modal('hide');//关闭modal
								window.location.reload();//刷新当前页
							}else{
								gritterError(obj.msg);
							}
						},
						error:function(obj){
							gritterError("您无权操作此项");
						}
					});
					$( this ).dialog( "close" );
				}
			}
			,
			{
				html: "<i class='ace-icon fa fa-times bigger-110'></i>取消",
				"class" : "btn btn-minier",
				click: function() {
					$( this ).dialog( "close" );
				}
			}
		]
	});
}

/**
 * 禁用用户
 * @param obj
 * @returns
 */
function disableUser(obj){
	$( "#dialog-confirm-disable" ).removeClass('hide').dialog({
		resizable: false,
		width: '320',
		modal: true,
		title: "系统提示",
		title_html: true,
		buttons: [
			{
				html: "<i class='ace-icon fa fa-trash-o bigger-110'></i>禁用",
				"class" : "btn btn-danger btn-minier",
				click: function() {
					var id = obj.id.replace('disable-','').replace('-disable','');
					$.ajax({
						url: '/admin/sys/user/disable',
						data: {"id":id},
						dataType: 'json',
						async: false,
						success:function(obj){
							if(obj.status == 200){
								gritterSuccess(obj.data);
								//$('#userModel').modal('hide');//关闭modal
								window.location.reload();//刷新当前页
							}else{
								gritterError(obj.msg);
							}
						},
						error:function(obj){
							gritterError("您无权操作此项");
						}
					});
					$( this ).dialog( "close" );
				}
			}
			,
			{
				html: "<i class='ace-icon fa fa-times bigger-110'></i>取消",
				"class" : "btn btn-minier",
				click: function() {
					$( this ).dialog( "close" );
				}
			}
		]
	});
}

/**
 * 头像上传窗口
 */
$('#input-file-faceImage').ace_file_input({
	style: 'well',
	btn_choose: '点击或将头像拖动到此处进行上传',
	btn_change: null,
	no_icon: 'ace-icon fa fa-picture-o',
	droppable: true,
	thumbnail: 'large',//large | fit | small
	allowExt: ["jpeg", "jpg", "png", "gif" , "bmp"],
	allowMime: ["image/jpg", "image/jpeg", "image/png", "image/gif", "image/bmp"]
	
	//,icon_remove:null//set null, to hide remove/reset button
	/**,before_change:function(files, dropped) {
		//Check an example below
		//or examples/file-upload.html
		return true;
	}*/
	/**,before_remove : function() {
		return true;
	}*/
	,
	preview_error : function(filename, error_code) {
		//error_code values
		//1 = 'FILE_LOAD_FAILED',
		//2 = 'IMAGE_LOAD_FAILED',
		//3 = 'THUMBNAIL_FAILED'
		//alert(error_code);
	}

}).on('change', function(){
	//console.log($(this).data('ace_input_files'));
	//console.log($(this).data('ace_input_method'));
});

/**
 * 打开头像上传模态框
 * @param obj
 * @returns
 */
var uploadUserId;
function uploadModal(id){
	var userId = id.replace('upload-', '');
	uploadUserId = userId;
	$('#uploadFaceImageModal').modal('show');
}

/**
 * 用户头像上传
 * @returns
 */
$('#form-faceImage-btn').on('click', function(){
	var formData = new FormData();
	var file = document.getElementById('input-file-faceImage').files[0];
	if(file != null){
		formData.append('file', file);
		upload('/admin/sys/user/uploadFaceImage?userId=' + uploadUserId, formData);
	}else {
		return false;
	}
})

/**
 * 异步请求上传文件
 * @param url
 * @param data
 * @returns
 */
function upload(url, data){
	$.ajax({
		url: url,
		data: data,
		method: 'post',
		dataType: 'json',
		async: false,
		contentType:false,
		processData:false,
		success: function(obj){
			if(obj.status == 200){
				gritterSuccess(obj.msg);
				$('#upload-' + uploadUserId + ' img').attr('src', obj.data);//实时显示最新头像
				$('#uploadFaceImageModal').modal('hide');
				$('.ace-file-input').find('a[class="remove"]').trigger('click');//清除文件上传框中的内容
				//window.location.reload();//刷新页面
			}else{
				gritterError(obj.msg);
			}
		},
		error: function(obj){
			gritterError('您无权操作此项');
		}
	});
}

/**
 * 点击发送邮件，显示加载中的图标
 * @returns
 */
$('.send-email-form').on('submit', function(){
	$('.main-content').append('<div class="message-loading-overlay"><i class="fa-spin ace-icon fa fa-spinner orange2 bigger-300"></i></div>');
});

//$('.page-btn').on('click', function(e){
//	$(this).addClass('active');
//});